# services.py
import random
from models import User, Card

class ATMService:
    def __init__(self, repository):
        self.repository = repository

    def _random_card_id(self):
        while True:
            card_id = ''.join(random.choice('0123456789') for _ in range(6))
            if not self.repository.get_user(card_id):
                return card_id

    def create_user(self, name, user_id, phone, prest_money, password):
        if prest_money < 0:
            return "预存款不能为负数。"
        card_id = self._random_card_id()
        card = Card(card_id, password, prest_money)
        user = User(name, user_id, phone, card)
        self.repository.save_user(card_id, user)
        return f"开户成功，卡号为: {card_id}"

    def cancel_account(self, card_id):
        return self.repository.delete_user(card_id)

    def search_user(self, card_id, password):
        user = self.repository.get_user(card_id)
        if user and user.card.card_pwd == password:
            return f"卡号: {user.card.card_id}, 余额: {user.card.money:.2f}"
        return "卡号或密码错误。"
